package com.robusta.app.web.controller;

import com.robusta.app.api.SpreadsheetModelPersister;
import com.robusta.app.web.model.UploadViewModel;
import com.robusta.spreadsheet.model.exception.WorkbookException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.xml.bind.JAXBException;
import java.io.IOException;

@Controller
@RequestMapping("uploadSpreadsheet")
public class SpreadsheetUploadController {
    private SpreadsheetModelPersister modelPersister;

    @Autowired
    public SpreadsheetUploadController(SpreadsheetModelPersister modelPersister) {
        this.modelPersister = modelPersister;
    }

    @RequestMapping(method = RequestMethod.POST)
    public String acceptAndProcessUploadedSpreadsheet(@ModelAttribute("uploadModel") UploadViewModel model) throws IOException, JAXBException, WorkbookException {
        modelPersister.buildModelFromSpreadsheetAndPersist(model.getSelectedTemplate(), model.getUploadFile().getInputStream());
        return "redirect:home.html";
    }
}
